import React, { Component } from 'react'
import { 
    Card,
    Button,
    Table,
    Modal,
    message
} from "antd"
import { formateDate } from '../../utils/dataUtils'
import LinkButton from '../../components/link-button'
import { PAGE_SIZE } from '../../utils/constants'
import { reqDeleteUser, reqGetUesrsList, reqAddOrUpdateUser } from "../../api/index"
import { QuestionCircleOutlined } from "@ant-design/icons"
import UserForm from "./UserForm";

/*
    用户路由
 */
export default class User extends Component {
    constructor(props) {
        super(props)
        this.initColumns()
    }

    state = {
        users: [], // 所有用户列表
        roles: [], // 所有角色的列表
        isShow: false, // 是否显示添加或删除的确认框
        loading: false
    }

    initColumns = () => {
        this.columns = [
            {
                title: "用户名",
                dataIndex: "username",
            },
            {
                title: "邮箱",
                dataIndex: "email",
            },
            {
                title: "电话",
                dataIndex: "phone",
            },
            {
                title: "注册时间",
                dataIndex: "create_time",
                render: formateDate
            },
            {
                title: "所属角色",
                dataIndex: "role_id",
                render: (role_id) => this.roleNames[role_id] || "无所属角色" 
            },
            {
                title: "操作",
                render: (user) => (
                    <span>
                        <LinkButton onClick={() => this.showUpdate(user)}>修改</LinkButton>
                        <LinkButton onClick={() => this.deleteUser(user)}>删除</LinkButton>
                    </span>
                )
            }
        ]
    }

    // 根据role的数组, 生成包含所有角色名的对象
    initRoleNames = (roles) => {
        // 保存
        this.roleNames = roles.reduce((pre, role) => {
            pre[role._id] = role.name
            return pre
        }, {})
        

    }

    // 删除指定用户
    deleteUser = (user) => {
        Modal.confirm({
            title: `确认删除${user.username}吗?`,
            icon: <QuestionCircleOutlined />,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                const userId = user._id
                const result = await reqDeleteUser(userId)
                if(result.status === 0) {
                    message.success('删除用户成功!')
                    this.getUsers()
                }
            }
        })
    }

    // 显示修改页面
    showUpdate = (user) => {
        this.user = user // 保存
        this.setState({isShow: true})
    }

    // 显示添加页面
    showAdd = () => {
        this.user = null
        this.setState({isShow: true})
    }

    // 添加或更新user
    addOrUpdateUser = async() => {
        
        this.setState({isShow:false})
        // 1. 收集输入数据
        const user = this.userRef.current.getFieldValue()
        this.userRef.current.resetFields()
        // 如果是更新
        if(this.user && this.user._id) {
            user._id = this.user._id
        }

        // 2.提交添加的请求
        const result = await reqAddOrUpdateUser(user);
        // 3.更新列表显示
        if(result.status === 0) {
            message.success(`${this.user ? "修改" : "添加"}用户成功`)
            this.getUsers()
        }
    }

    getUsers = async() => {
        this.setState({loading: true})
        const result = await reqGetUesrsList()
        if(result.status === 0) {
            const {users, roles} = result.data
            this.initRoleNames(roles)
            this.setState({
                users,
                roles,
                loading:false
            })
        }
    }

    componentDidMount() {
        this.getUsers()
    }

    render() {
        const {users, isShow, loading, roles} = this.state;
        const user = this.user || {}
        const title = (
            <Button type="primary" onClick={this.showAdd}>创建用户</Button>
        )
        return (
            <Card title={title}>
                <Table
                    bordered
                    rowKey="_id" 
                    dataSource={users}
                    columns={this.columns}
                    pagination={{defaultPageSize: PAGE_SIZE}}
                    loading={loading} 
                />
                <Modal 
                    title={user._id ? "修改用户": "添加用户"} 
                    visible={isShow} 
                    onOk={this.addOrUpdateUser} 
                    onCancel={() => {this.setState({isShow:false})}}
                    destroyOnClose={true}
                >
                    <UserForm 
                        setUserForm={e => this.userRef = e} 
                        roles={roles}
                        user={user}
                    />
                </Modal>
            </Card>
        )
    }
}
